﻿using Abp.Json;
using AutoMapper;
using Castle.Core;
using Castle.Core.Logging;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Enum;
using IntelligentAgriculture.Domain.Impl;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Interface.IEarTagReposiotry;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using MathNet.Numerics.Differentiation;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services
{
    public class SheepAblactationService : ISheepAblactationService
    {
        /// <summary>
        /// 种母断奶仓储
        /// </summary>
        private readonly ISheepAblactationRepository _sheepAblactationRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 种母分娩仓储
        /// </summary>
        private readonly IDeliveryPromptModelRepository _deliveryPromptModelRepository;
        /// <summary>
        /// 栋舍仓储
        /// </summary>
        private readonly IridegRepository _iridegRepository;
        /// <summary>
        /// 栏位仓储
        /// </summary>
        private readonly IColumnManRepository _columnManRepository;
        /// <summary>
        /// 羊只档案仓储
        /// </summary>
        private readonly ISheepFileModelRepository _sheepFileModelRepository;
        /// <summary>
        /// 耳号仓储
        /// </summary>
        private readonly IEarTagReposiotry _earTagReposiotry;
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IUserRepository _userRepository;
        /// <summary>
        /// 种母历史记录仓储
        /// </summary>
        private readonly IHistoryRecordRepository _historicalDataRepository;
        /// <summary>
        /// 种母分娩仓储
        /// </summary>
        private readonly IParturitionRepository _parturitionRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SheepAblactationService> _logger;
        private readonly AgricultureDbContext _db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sheepAblactationRepository"> 种母断奶仓储</param>
        /// <param name="logger"> 日志</param>
        /// <param name="deliveryPromptModelRepository"> 种母分娩仓储</param>
        /// <param name="iridegRepository"> 栋舍仓储</param>
        /// <param name="columnManRepository"> 栏位仓储</param>
        /// <param name="mapper"> 映射器</param>
        /// <param name="sheepFileModelRepository">羊只档案仓储</param>
        /// <param name="userRepository">用户仓储</param>
        /// <param name="earTagReposiotry">耳号仓储</param>
        /// <param name="db">数据库上下文</param>
        /// <param name="historicalDataRepository">种母历史记录仓储</param>
        /// <param name="parturitionRepository">种母分娩仓储</param>
        public SheepAblactationService(ISheepAblactationRepository sheepAblactationRepository, ILogger<SheepAblactationService> logger, IDeliveryPromptModelRepository deliveryPromptModelRepository, IridegRepository iridegRepository, IColumnManRepository columnManRepository, IMapper mapper, ISheepFileModelRepository sheepFileModelRepository, IUserRepository userRepository, IEarTagReposiotry earTagReposiotry, AgricultureDbContext db, IHistoryRecordRepository historicalDataRepository, IParturitionRepository parturitionRepository)
        {
            _sheepAblactationRepository = sheepAblactationRepository;
            _logger = logger;
            _deliveryPromptModelRepository = deliveryPromptModelRepository;
            _iridegRepository = iridegRepository;
            _columnManRepository = columnManRepository;
            _mapper = mapper;
            _sheepFileModelRepository = sheepFileModelRepository;
            _userRepository = userRepository;
            _earTagReposiotry = earTagReposiotry;
            _db = db;
            _historicalDataRepository = historicalDataRepository;
            _parturitionRepository = parturitionRepository;
        }
        /// <summary>
        /// 获取档案表母羊在哺乳的耳号列表
        /// </summary>
        /// <returns>包含母羊在哺乳状态的耳号信息的列表</returns>
        public async Task<List<Eartag>> GetEweEarTagsFromSheepFile()
        {
            try
            {
                // 获取档案表里的母羊在哺乳的耳号
                var sheepfile = await _sheepAblactationRepository.GetEweEarTagsFromSheepFile();
                //羊只类型为种母，在哺乳状态
                sheepfile = sheepfile.Where(p => p.SheepType == 2 && p.ReproductionState == 8 && p.PresentState == 1).ToList();

                // 创建一个 string 类型的 list 集合用来存储查询到的耳号
                List<string> earTags = sheepfile.Select(s => s.EarTag).ToList()!;

                //获取所有耳号的信息
                var earTagDetails = await _earTagReposiotry.GetShow();
                // 过滤掉已经删除的耳号
                earTagDetails = earTagDetails.Where(e => e.Isdel == false);

                // 根据 earTags 里的耳号，去耳号表获取对应耳号信息
                var matchingEarTags = earTagDetails.Where(e => earTags.Contains(e.EarTagNumber!)).ToList();

                // 返回包含母羊在哺乳状态的耳号信息的列表
                return matchingEarTags;

            }
            catch (Exception ex)
            {
                _logger.LogError("获取档案表母羊在哺乳的耳号列表失败！" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 获取羊只当前的档案里的栋舍Id
        /// </summary>
        /// <param name="earTagNumber">耳号</param>
        /// <returns></returns>
        public async Task<List<Sheepfilemodel>> GetBuildByEar(string earTagNumber)
        {
            try
            {
                //获取所有羊只档案表数据
                var sheepfile = await _sheepAblactationRepository.GetEweEarTagsFromSheepFile();
                sheepfile = sheepfile.Where(p => p.EarTag == earTagNumber).ToList();
                return sheepfile;
            }
            catch (Exception ex)
            {
                _logger.LogError("获取羊只当前的栋舍失败！" + ex.Message);
                throw;
            }
        }
        /// <summary>
        /// 添加种母断奶
        /// </summary>
        /// <param name="sheepAblactations">添加种母断奶的</param>
        /// <returns></returns>
        public async Task<int> AddSheepAblactation(List<Sheepablactation> sheepAblactations)
        {
            #region 
            //try
            //{
            //    //单据号为雪花Id
            //    //string document = "ZMDN" + YitIdHelper.NextId().ToString();
            //    //获取种母分娩的数据
            //    //var childbirths = _deliveryPromptModelRepository.GetDeliverypromptmodels().Where();
            //    //获取种母分娩列表
            //    //var delivery = _deliveryPromptModelRepository.GetDeliverypromptmodels();
            //    sheepAblactations.ForEach(p =>
            //    {
            //        p.DocumentNumber = "ZMDN" + YitIdHelper.NextId().ToString();
            //        p.CreateName = _userRepository.GetUsers().FirstOrDefault(c => c.Uid == p.UserId).Uname;
            //        p.CreateTime = DateTime.Now;
            //        p.AuditDate = null;
            //        p.AuditName = null;
            //        p.UpdateTime = null;
            //        p.UpdateName = null;
            //        p.IsDel = false;
            //    });
            //    //添加到种母断奶表
            //    await _sheepAblactationRepository.AddSheepAblactation(sheepAblactations);
            //    //更新羊只档案表中关于断奶的相关信息
            //    var sheepfile = await _sheepFileModelRepository.GetSheepfilemodels();
            //    //更新种母历史记录表中相关字段
            //    var deliveryHistory = await _historicalDataRepository.GetHistoryRecordsAsync();
            //    foreach (var item in sheepAblactations)
            //    {
            //        var sheep = sheepfile.FirstOrDefault(p => p.EarTag == item.EarTag);
            //        if (sheep == null)
            //        {
            //            break;
            //        }
            //        sheep.AblactationWeight = item.BreedingWeight;
            //        sheep.AblactationDate = item.Ablactation;
            //        sheep.BirthContent = item.AblactationCause;
            //        sheep.BuildingId = item.ToBuildingManageId;
            //        sheep.ColumnId = item.ToColumMangementId;
            //        sheep.ReproductionState = 6;
            //        //修改羊只档案表数据
            //        _sheepFileModelRepository.UpdaSheepFileModel(sheep);

            //        var deliverys = deliveryHistory.FirstOrDefault(p => p.EarTag == item.EarTag);
            //        if (deliverys == null)
            //        {
            //            break;
            //        }
            //        deliverys.WeaningDate = item.Ablactation;
            //        deliverys.WeaningCount = item.AblactationNum;
            //        deliverys.WeaningWeight = item.AblactationWeight;
            //        //修改种母历史记录表数据
            //        await _historicalDataRepository.UpdateHisRecordAsync(deliverys);
            //    }
            //    //修改到数据库
            //    await _db.SaveChangesAsync();
            //    tran.Commit();
            //    return 1;
            //}
            //catch (Exception ex)
            //{
            //    _logger.LogError("添加种母断奶失败！" + ex.Message);
            //    tran.Rollback();
            //    throw;
            //}
            #endregion
            using (var tran = _db.Database.BeginTransaction())
            {
                try
                {
                    foreach (var item in sheepAblactations)
                    {
                        //单据号为雪花Id
                        item.DocumentNumber = "ZMDN" + YitIdHelper.NextId().ToString();
                        item.CreateName = _userRepository.GetUsers().FirstOrDefault(c => c.Uid == item.UserId)?.Uname;
                        item.CreateTime = DateTime.Now;
                        item.AuditDate = null;
                        item.AuditName = null;
                        item.UpdateTime = null;
                        item.UpdateName = null;
                        item.IsDel = false;
                    }

                    // 添加到种母断奶表
                    await _sheepAblactationRepository.AddSheepAblactation(sheepAblactations);
                    await _db.SaveChangesAsync();

                    // 获取羊只档案
                    var sheepfile = await _sheepFileModelRepository.GetSheepfilemodels();
                    // 获取种母历史记录
                    var deliveryHistory = await _historicalDataRepository.GetHistoryRecordsAsync();
                    //获取种母分娩
                    var childbirth = await _parturitionRepository.GetChildbirth();

                    foreach (var item in sheepAblactations)
                    {
                        // 根据添加的羊只耳号修改羊只档案表数据
                        var sheep = sheepfile.FirstOrDefault(p => p.EarTag == item.EarTag);
                        if (sheep != null)
                        {
                            sheep.AblactationWeight = item.BreedingWeight;
                            sheep.AblactationDate = item.Ablactation;
                            sheep.BirthContent = item.AblactationCause;
                            sheep.BuildingId = item.ToBuildingManageId;
                            sheep.ColumnId = item.ToColumMangementId;
                            sheep.ReproductionState = 6;

                            await _sheepFileModelRepository.UpdaSheepFileModel(sheep);
                        }
                        // 根据添加的羊只耳号修改种母历史记录表数据
                        var deliverys = deliveryHistory.FirstOrDefault(p => p.EarTag == item.EarTag);
                        if (deliverys != null)
                        {
                            deliverys.WeaningDate = item.Ablactation;
                            deliverys.WeaningCount = item.AblactationNum;
                            deliverys.WeaningWeight = item.AblactationWeight;

                            await _historicalDataRepository.UpdateHisRecordAsync(deliverys);
                        }
                        else
                        {
                            break;
                        }
                        // 根据添加的羊只耳号修改种母分娩表数据
                        var child = childbirth.FirstOrDefault(p => p.EarTag == item.EarTag);
                        if (child != null)
                        {
                            child.Isdel = true;
                            await _parturitionRepository.UpdateChildbirth(child);
                        }
                        else
                        {
                            break;
                        }

                        //向羊只转舍表添加数据
                        var sheepRescission = new Sheeprescission()
                        {
                            SheepRescissionDate = item.Ablactation,
                            EarTag = item.EarTag,
                            RoundType = 5,
                            OutBuildingManageId = item.CurrentBuilding,
                            OutColumMangementId = item.CurrentField,
                            ToBuildingManageId = item.ToBuildingManageId,
                            ToColumMangementId = item.ToColumMangementId,
                            SheepType = 2,//种母
                            Variety = sheepfile.FirstOrDefault(p => p.EarTag == item.EarTag)!.Variety,
                            SheepRescissionSex = false,
                            CreateName = item.CreateName,
                            CreateTime = item.CreateTime,
                            UpdateName = item.UpdateName,
                            UpdateTime = item.UpdateTime,
                            DocumentNumber = item.DocumentNumber,
                            Isdel = false
                        };
                        await _db.Sheeprescissions.AddAsync(sheepRescission);
                    }
                    await _db.SaveChangesAsync();
                    //事务提交
                    tran.Commit();
                    return 1;
                }
                catch (Exception ex)
                {
                    // 日志记录失败信息
                    _logger.LogError("添加种母断奶失败！" + ex.Message);
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }
        /// <summary>
        /// 获取种母断奶列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageOutput<SheepAblactationOutput>> GetSheepAblactation(SheepAblactationInput input)
        {
            try
            {
                //获取羊只档案表里的所有数据
                var sheepFile = await _sheepFileModelRepository.GetSheepfilemodels();
                //获取负责人信息
                var user = _userRepository.GetUsers();
                // 获取种母断奶列表
                var sheepablationList = await _sheepAblactationRepository.GetSheepAblactations();
                // 获取栋舍表和栏位表
                var buildings = _iridegRepository.Showinfo();
                var columns = _columnManRepository.GetShow();

                // 断奶开始日期筛选
                //使用 DateTime.TryParse 代替 Convert.ToDateTime，可以避免格式不正确时抛出异常。
                if (DateTime.TryParse(input.AblactationAction, out var startDate))
                {
                    sheepablationList = sheepablationList.Where(c => c.Ablactation >= startDate).ToList();
                }
                // 断奶结束日期筛选
                if (DateTime.TryParse(input.AblactationEnd, out var endDate))
                {
                    sheepablationList = sheepablationList.Where(c => c.Ablactation <= endDate).ToList();
                }
                // 耳号筛选
                //使用 StringComparison.OrdinalIgnoreCase 进行不区分大小写的字符串匹配。
                if (!string.IsNullOrEmpty(input.EarTag))
                {
                    sheepablationList = sheepablationList.Where(c => c.EarTag!.Contains(input.EarTag, StringComparison.OrdinalIgnoreCase)).ToList();
                }
                // 栋舍筛选
                if (input.ToBuildingManageId > 0)
                {
                    sheepablationList = sheepablationList.Where(c => c.ToBuildingManageId == input.ToBuildingManageId).ToList();
                }
                // 负责人筛选
                if (input.UserId > 0)
                {
                    sheepablationList = sheepablationList.Where(c => c.UserId == input.UserId).ToList();
                }
                var newlist = (from sa in sheepablationList
                               join bu in buildings
                               on sa.CurrentBuilding equals bu.RidgepoleId
                               join co in columns
                               on sa.CurrentField equals co.ColumnManagementId
                               where sa.IsDel == false
                               select new SheepAblactationOutput()
                               {
                                   AblactationId = sa.AblactationId,
                                   EarTag = sa.EarTag,
                                   Ablactation = sa.Ablactation,
                                   SuckleNum = sa.SuckleNum,
                                   BreedingWeight = sa.BreedingWeight,
                                   AblactationNum = sa.AblactationNum,
                                   AblactationWeight = sa.AblactationWeight,
                                   CurrentBuilding = sa.CurrentBuilding,
                                   CurrentField = sa.CurrentField,
                                   ToBuildingManageId = sa.ToBuildingManageId,
                                   ToColumMangementId = sa.ToColumMangementId,
                                   CreateName = sa.CreateName,
                                   UserId = sa.UserId,
                                   CreateTime = sa.CreateTime,
                                   UpdateName = sa.UpdateName,
                                   UpdateTime = sa.UpdateTime,
                                   AuditName = sa.AuditName,
                                   AuditDate = sa.AuditDate,
                                   DocumentNumber = sa.DocumentNumber,
                                   AblactationCause = sa.AblactationCause,
                                   IsDel = sa.IsDel,
                                   NowRidgepoleName = buildings.FirstOrDefault(p => p.RidgepoleId == sa.CurrentBuilding).RidgepoleName,
                                   NowColumnName = columns.FirstOrDefault(p => p.ColumnManagementId == sa.CurrentField).ColumnName,
                                   GoRidgepoleName = buildings.FirstOrDefault(p => p.RidgepoleId == sa.ToBuildingManageId).RidgepoleName,
                                   GOColumnName = columns.FirstOrDefault(p => p.ColumnManagementId == sa.ToColumMangementId).ColumnName,
                                   UserName = user.FirstOrDefault(p => p.Uid == sa.UserId).Uname
                               });
                // 分页处理
                var totalCount = newlist.Count();
                var pagedData = newlist.OrderByDescending(p => p.CreateTime).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
                // 映射到输出模型
                //var outputData = _mapper.Map<List<SheepAblactationOutput>>(pagedData);
                var result = new PageOutput<SheepAblactationOutput>
                {
                    PageSize = input.PageSize,
                    TotalCount = totalCount,
                    Data = pagedData
                };
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError("获取种母断奶列表失败！" + ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 逻辑删除种母断奶
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DelSheepAblacations(int userId, params int[] ids)
        {
            try
            {
                //删除种母断奶
                var res = await _sheepAblactationRepository.DelSheepAblacations(userId, ids);
                //获取羊只断奶表数据
                //var sheepablacation = await _sheepAblactationRepository.GetSheepAblactations();
                ////获取种母分娩
                //var childbirth = await _parturitionRepository.GetChildbirth();
                ////获取所有耳号
                ////根据ids去羊只断奶查出相应的数据
                //foreach (var id in ids)
                //{
                //    var ear = sheepablacation.FirstOrDefault(p => p.AblactationId == id).EarTag;
                //    var child = childbirth.FirstOrDefault(p => p.EarTag == ear);
                //    child.Isdel = false;
                //    _db.Childbirths.Update(child);
                //}
                //await _db.SaveChangesAsync();
                return res;
            }
            catch (Exception ex)
            {
                _logger.LogError("删除种母断奶失败！" + ex.Message);
                throw;
            }
        }
    }
}